package nancal.mp.mvc.iam

import io.swagger.annotations.Api
import nancal.mp.db.mongo.mor
import nbcp.base.comm.JsonResult
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.CipherUtil
import nbcp.myoql.db.mongo.query
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

@Api(description = "重置密码", tags = arrayOf("reset-pwd"))
@RestController
@RequestMapping("/iam-tenant-user")
class TenantUserLoginController {

    @PostMapping("/reset-pwd")
    fun resetPwd(
        loginName: String,
        request: HttpServletRequest
    ): JsonResult {
        mor.tenant.tenantLoginUser.query()
            .apply {
                if (loginName.HasValue){
                    this.linkOr(
                        { it.loginName mongoEquals loginName },
                        { it.mobile mongoEquals loginName },
                        { it.email mongoEquals loginName }
                    )
                }
            }
            .toList()
            .apply {
                if (this.any()){
                    this.forEach { user ->
                        mor.tenant.tenantLoginUser.updateById(user.id)
                            .set { it.password to CipherUtil.encryptWithSHA256(CipherUtil.encryptWithSHA256("1234") + user.passwordSalt) }
                            .exec()
                    }
                }
            }

        return JsonResult()
    }
}